package com.zhengx.blehelper;


import android.util.Log;

import java.nio.ByteBuffer;

/**
 * name：IMessageDecoder
 * class: 解码接口，自己扩展
 * author: zhengx
 * create_time: 2018/10/29
 */
public abstract class MessageDecoder {

    private static final String TAG = MessageDecoder.class.getSimpleName();

    /*数据临时缓冲区*/
    private ByteBuffer mReadByteBuf;

    private BleCallback.OnReadMsgCallback onReadMsgCallback;

    public MessageDecoder() {
        mReadByteBuf = ByteBuffer.allocate(1024);
    }

    protected void addMessage(byte[] source) {
        if (decode(source)) {
            mReadByteBuf.put(source);
            mReadByteBuf.flip();
            byte[] temp = new byte[mReadByteBuf.limit()];

            try {
                mReadByteBuf.get(temp, mReadByteBuf.position(), mReadByteBuf.limit());
            }catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "数据读取错误！");
                return;
            }

//            if (temp.length < 2) {
//                Log.e(TAG, "temp size:" + temp.length);
//                return;
//            }
            mReadByteBuf.clear();

            if (onReadMsgCallback != null) {
                onReadMsgCallback.onRead(temp);
            }
        } else {
            mReadByteBuf.put(source);
        }
    }

    public abstract boolean decode(byte[] source);

    public void setOnReadMsgCallback(BleCallback.OnReadMsgCallback onReadMsgCallback) {
        this.onReadMsgCallback = onReadMsgCallback;
    }

}
